<template>
  <div class="bg-plus">
    <div class="form-container">
      <div class="table">
        <el-table style="width: 100%" :data="enterpriseList">
          <el-table-column type="index" label="序号" />
          <el-table-column label="企业名称" prop="enterpriseName" />
          <el-table-column label="租赁楼宇" prop="buildingName" />
          <el-table-column label="租赁时间" prop="temporary" />
          <el-table-column
            label="操作"
            show-overflow-tooltip
          >
            <template #default="scope">
              <el-button
                size="mini"
                type="text"
                @click="showAddRentDialog(scope.row)"
              >续签</el-button>
              <el-button
                type="text"
                @click="outRentFn(scope.row.contractId)"
              >退租</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div v-if="totalFlag">
      <el-pagination
        class="pagination"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="100"
        layout="total, prev, pager, next, sizes"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 点击续租弹窗 -->
    <el-dialog title="续租合同" :visible.sync="rentDialogVisible" width="580px">
      <!-- 表单区域 -->
      <div class="form-container" />
      <!-- 表单模版 -->
      <div class="form-container">
        <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" disabled placeholder="请选择">
              <el-option
                :key="rentForm.buildingId"
                :label="rentForm.buildingName"
                :value="rentForm.buildingId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              unlink-panels
              type="daterange"
              range-separator="至"
              :start-placeholder="setMonthly()"
              :picker-options="pickerOptions"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
            <!--
              range-separator="至"
              :start-placeholder="setMonthly()"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
             -->
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload
              ref="uploadList"
              v-model="rentForm.contractId"
              action="#"
              :http-request="uploadHandle"
              :before-upload="beforeUpload"
              :limit="1"
            >
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <!--
          slot="tip" 提示说明文字 Vue旧语法
          slot="tip" 等价于 v-solt:tip 或者 #tip
          slot-scope="scope" 等价于 v-slot="scope"
         -->
              <div slot="tip" class="el-upload__tip">支持扩展名：.doc .docx .pdf, 文件大小不超过5M</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="{rentDialogVisible =false}">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmAdd">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getTemporaryListAPI, editRenewLeaseAPI } from '@/apis/workben'
import { outRentAPI, uploadAPI } from '@/apis/park'
export default {
  data() {
    return {
      params: {
        page: 1,
        pageSize: 10
      },

      warningList: [],
      enterpriseList: [], // 临期合同提醒
      total: 0, // 获取临期企业的分页
      totalFlag: false, // 给临期企业设置开关
      rentDialogVisible: false, // 续租合同弹窗
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业id
        type: 0, // 合同类型 (0 租赁 ， 1 续租)
        rentTime: [] // 合同时间
      },
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件' }
        ]
      },
      pickerOptions: {
        disabledDate(time) {
          const today = new Date()
          const nextMonthFirstDay = new Date(today.getFullYear(), today.getMonth() + 1, 1)
          return time.getTime() < nextMonthFirstDay.getTime()
        }
      }
    }
  },
  created() {
    this.getTemporaryList()
  },
  methods: {
    // 分页方法
    handleSizeChange(nextPageSize) {
      this.params.pageSize = nextPageSize
      this.getTemporaryList()
    },
    handleCurrentChange(nextPage) {
      this.params.page = nextPage
      this.getTemporaryList()
    },
    // 获取临期企业
    async getTemporaryList() {
      const res = await getTemporaryListAPI(this.params)
      console.log(res)
      this.total = res.data.total
      this.totalFlag = true
      const newArr = res.data.rentAdvent.map(item => ({
        id: item.id,
        buildingId: item.buildingId,
        buildingName: item.buildingName,
        // 获取临期企业是不能将旧的合同id赋值，否则新上传弹窗空白点击提交时无法正常校验合同id
        // contractId: item.contractId,
        enterpriseId: item.enterpriseId,
        enterpriseName: item.enterpriseName,
        temporary: item.startTime + ' 至 ' + item.endTime
      }))
      this.enterpriseList = newArr
    },
    async confirmAdd() {
      await this.$refs.addForm.validate()
      const obj = {
        ...this.rentForm
      }
      obj.startTime = this.rentForm.rentTime[0]
      obj.endTime = this.rentForm.rentTime[1]
      delete obj.rentTime
      // console.log(obj)
      const res = await editRenewLeaseAPI(obj)
      // const res = await createRentAPI(obj)
      // console.log(res)
      // 当文件上传成功后，需要清空表单，否则点开表单依然保留上一次数据
      this.$message({
        message: res.msg,
        type: 'success'
      })
      this.$refs.addForm.resetFields()
      this.$refs.uploadList.clearFiles()
      this.rentDialogVisible = false
    },
    // 打开续租合同弹窗
    showAddRentDialog(row) {
      // console.log(id)
      this.rentForm = row
      this.rentDialogVisible = true
    },
    // 上传传租赁合同
    async uploadHandle(file) {
      const theFile = file.file
      const fd = new FormData()
      fd.append('file', theFile)
      fd.append('type', 'contract')
      const res = await uploadAPI(fd)
      // console.log(res)
      this.rentForm.contractId = res.data.id
      this.rentForm.contractUrl = res.data.url
      await this.$refs.addForm.validateField('contractId')
    },
    // 上传前校验
    beforeUpload(file) {
      // console.log(file)
      const list = ['application/msword', 'application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
      const isDoc = list.includes(file.type)
      const isSize = (file.size / 1024 / 1024 < 5)
      if (!isDoc) {
        this.$message.error('上传文件只能是 doc / docx / pdf 格式！')
      }
      if (!isSize) {
        this.$message.error('上传的文件大小不能超过5MB')
      }
      if (isDoc && isSize) {
        return true
      } else {
        return Promise.reject('取消上传')
      }
    },
    // 续租时-设置下个月1日起始
    setMonthly() {
      const date = new Date()
      // 获取各个时间部分
      let year = date.getFullYear()
      let month = String(date.getMonth() + 1).padStart(2, '0') // 月份从0开始，所以需要加1
      // 临期为下个月，所以月份要+1，当月份为12时，年+1
      // console.log(month)
      if ((month + 1) === 13) {
        year++
        month = 1
      } else {
        month++
      }
      const str = `${year}-${month}-01`
      return str
    },
    // 企业退租功能-退租的id为合同id，不是列表和企业id
    async outRentFn(id) {
      // console.log(row)
      // return
      // const id = row.enterpriseId
      // const
      // console.log(id)
      this.$confirm('确定要退租吗？', '提示', {
        confirmButtonText: '确定',
        concelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await outRentAPI(id)
        // const res = await getRentListAPI(id)
        // eslint-disable-next-line no-undef
        // row.list = res.data
        this.getEnterpriseList()
        this.$message({
          type: 'success',
          message: '退租成功'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消退租'
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">
.pagination{
  text-align: right;
  margin-top: 10px;
}
</style>
